package com.myapp.wicket;

import Entities.*;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;

import org.apache.wicket.extensions.markup.html.repeater.util.SortableDataProvider;
import org.apache.wicket.model.IModel;
import org.apache.wicket.model.Model;


public class ProductsProvider extends SortableDataProvider<Product> 
{               private List<Product> pList;
        
		public ProductsProvider(List<Product> pList) {
			setSort("id", true);
                        this.pList=pList;
		}
                public Iterator<? extends Product> iterator(int first, int count) {
			List<Product> data = new ArrayList<Product>(pList);
			Collections.sort(data, new Comparator<Product>() 
                        {
                            public int compare(Product o1, Product o2)
                            {
					int dir = getSort().isAscending() ? 1 : -1;
                                        if ("name".equals(getSort().getProperty())) {
						return dir * (o1.name.compareTo(o2.name));
					} else {
						return dir * ( Double.compare(o1.currentPrice,o2.currentPrice));
					}
		            }
			});
			return data.subList(first, Math.min(first + count, data.size())).iterator();
		}
                public int size()
                {
	          return pList.size();
		}
                public IModel<Product> model(Product object) 
                {
		  return Model.of(object);
		}
}
